<?php
class member extends table
{
	protected $_name	= 'my_member';
	protected $fields	= array('id','wid','email','username','password','province','city','name','tel','fax','login_time','register_time');
	protected $_primary = 'id';
	
	public static function needLogin()
	{
		if (!self::isLogin())
		{
			die('<script language=javascript>window.location="/app/?m=member&a=login";</script>');
		}
	}

	public static function cookiehash($username, $ip, $useragent)
	{
		
		$s = md5($username . $ip . $useragent) . md5(date('Y.m.d'));
		return md5($s);
	}
	
	public static function isLogin()
	{
		if (isset($_COOKIE['user'],$_COOKIE['username']) 
			&& $_COOKIE['user'] == 
			self::cookiehash($_COOKIE['username'],get_real_ip(),$_SERVER['HTTP_USER_AGENT']))
			return true;
		else return false;
	}

	public static function checkUsername($username)
	{
		$db		= self::db();
		$query	= $db->select()->from('my_member')->where("username='{$username}'");
		$result	= $db->fetchRow($query);
		return !($result) ? true : false;
	}
	
	public  function login($arg)
	{
		require_once ROOT . 'libs/Zend/Auth.php';
		require_once ROOT . 'libs/Zend/Auth/Adapter/DbTable.php';
		require_once ROOT . 'libs/Zend/Auth/Storage/Session.php';

		$db				= self::db();
		$auth			= Zend_Auth::getInstance();
		$authAdapter	= new Zend_Auth_Adapter_DbTable($db,'my_member','username','password');

		$authAdapter->setIdentity($arg['username'])->setCredential(md5($arg['password']));

		$result			= $auth->authenticate($authAdapter);

		if($result->isValid())
		{
			$storage = $auth->getStorage();
			$user	= (array)$authAdapter->getResultRowObject($this->fields);
			base::init('member')->update(array('login_time'=>time()),array('id'=>$user['id']));
			#Zend_Session::rememberMe();
			$storage->write($authAdapter->getResultRowObject($this->fields));
			return $user;
		}
		else 
		{
			return FALSE;
		}
	}
	
	public static function getInfo()
	{
		require_once ROOT . 'libs/Zend/Auth.php';
		
		$db				= parent::db();
		
		$auth			= Zend_Auth::getInstance();
		$user			= (array)$auth->getIdentity();
		$user			= base::init('member')->fetchRow("id={$_COOKIE['uid']}");
		$sql			= "select * from my_member_group as m,my_member_group_control as g where g.member_group_id=m.id and g.member_id={$user['id']}";
		$user['group']	= $db->fetchRow($sql);
		$user['score']	= base::init('score')->fetchRow(array('id'=>$user['id']));

		return $user;
	}
	
	public static function logout()
	{
		require_once ROOT. 'libs/Zend/Auth.php';
		require_once ROOT . 'libs/Zend/Auth/Storage/Session.php';
		
		session_start();
		$auth	= Zend_Auth::getInstance();
		Zend_Session::destroy(false,true);
		return 		$auth->clearIdentity();;
	}
}
